#include "Server.h"
#include "memory"
#include <iostream>

using namespace std;
using namespace server;

static void usage(const string &process)
{
    cerr << "usage:\n\t" << process << " port"
         << "\n\n";
}

static void webCalculateService(const Request &request, Response &response)
{
    switch (request._oper)
    {
    case '+':
        response._result = request._num1 + request._num2;
        break;

    case '-':
        response._result = request._num1 - request._num2;
        break;

    case '*':
        response._result = request._num1 * request._num2;
        break;

    case '/':
    {
        if (request._num2 == 0)
        {
            response._exitcode = DIVIDE_ZERO;
        }
        else
        {
            response._result = request._num1 / request._num2;
        }
    }
    break;

    case '%':
        if (request._num2 == 0)
        {
            response._exitcode = MODE_ZERO;
        }
        else
        {
            response._result = request._num1 % request._num2;
        }
        break;

    default:
        response._exitcode = OPERATOR_ERROR;
        break;
    }

} //@end void webCalculateService(const Request& request, Response& response)

void startService(Connection* connection)
{
    string request_package; // 存储一个完整的包文

    while (parseOnePackage(connection->_in_buffer, &request_package)) // 只要能获取到一个完整包文就继续下去
    {
        // task 为读到的包文去掉报头
        std::string request_text(removeHeader(request_package));
        if (request_text == "")
        {
            logMessage(ERROR, "remove request_package header fail!");
            return;
        }
        logMessage(NORMAL, "remove request_package header success! %s", request_text.c_str());

        // task 为request反序列化
        Request request;
        if (!request.unserialize(request_text))
        {
            logMessage(ERROR, "request unserialize fail!");
            return;
        }
        logMessage(NORMAL, "request unserialize success!");

        // task 调用service来处理从request中提取的数据(处理业务)，并把结果存进response中
        Response response;
        webCalculateService(request, response);

        // task 为response序列化
        std::string response_text;
        if (!response.serialize(&response_text))
        {
            logMessage(ERROR, "response serialize fail!");
            return;
        }
        logMessage(NORMAL, "response serialize success! %s", response_text.c_str());

        // task 为response_text添加报头构成包文
        std::string response_package(addHeader(response_text));
        logMessage(NORMAL, "response_text addHeader success! %s", response_package.c_str());

        // 将得到的响应包文存入输出缓冲区中，待该连接的所有请求都处理完后一起发送
        connection->_out_buffer += move(response_package);

    } //@end while(true)

    // 将处理完的所有响应包文一起发回给客户端
    if (connection->_send_method) connection->_send_method(connection);

} //@end void startService()

int main()
{
}